# -*- coding: utf-8 -*-

import requests
from requests.adapters import HTTPAdapter


def _get_partical(url, start, end):
    # 配置重试次数
    with requests.Session() as s:
        s.mount('http://', HTTPAdapter(max_retries=3))
        s.mount('https://', HTTPAdapter(max_retries=3))
        resp = s.get(url, headers={'Range': 'bytes=%d-%d' % (start, end)})
        if resp.status_code != 206:
            raise Exception('http error code %s when get %s' %
                            (resp.status_code, url))

            # 判断是否能正确获取文件流大小
        crange = resp.headers.get('Content-Range')
        if not crange:
            raise Exception('no content-range object found')

        div = crange.rfind('/')
        if div < 0:
            raise Exception('no content-range object found')
        csize = int(crange[div + 1:])
        return resp.content, csize


class UrlFileBuf(object):
    def __init__(self, url, pre_read_size=0):
        self._url = url
        self._buf = bytearray()
        self._fcsr = 0
        self.fize_size = 0
        # 预读取
        self.read(pre_read_size)

    def read(self, size):
        lb = len(self._buf)
        if size > lb:
            nb, self.file_size = _get_partical(self._url, lb, size - 1)
            self._buf.extend(nb)
        return self._buf[:size]
